import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Message, ButtonGroup,Loading } from 'tinper-bee';
import ApprovalModal from './ApprovalModal';
import ShowApprovalModal from './ShowApproval';
import mirror, { connect, actions } from "mirrorx";
import model from "./model";
import request from 'utils/request';

mirror.model(model);
const propTypes = {
    iconType: PropTypes.string,//图标的className，必填
};

const defaultProps = {

};


class Approval extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showLoading:false,
            showApprovalListModal:false
        };
    }
    async componentDidMount() { 
       
    }

    onCloseApproval = (obj) => {
        let {bpmService} = this.props;
        let {ButtonType} = this.state;
        let {data,type} = obj
        if(ButtonType == "CheckApprove") {
            this.setState({showApprovalListModal:false})
            return;
        }
        // this.ShowApprove(bpmService.CheckApprove); break;
        if(obj) {
            switch(ButtonType) {
                case "ButtonSubmit": this.ButtonApprovalSet(bpmService.ButtonSubmit); break;
                case "ButtonCallback": this.ButtonApprovalSet(bpmService.ButtonCallback); break;
                case "ButtonApprove": {
                    if(type != 1) {
                        this.ButtonApprovalSet2(bpmService.ButtonApprove,data); break;
                    }else {
                        this.ButtonApprovalSet1(bpmService.ButtonApprove,data); break;
                    }
                }
                case "ButtonCancelApprove": this.ButtonApprovalSet(bpmService.ButtonCancelApprove); break;
                case "ButtonCallBackApprove": this.ButtonApprovalSet(bpmService.ButtonCallBackApprove); break;
                
            }
        }
        this.setState({
            showApprovalModalModal:false
        })
    }

    ShowApprove = () => {
        let {showApprovalListModal} = this.state;
        this.setState({showApprovalListModal:!showApprovalListModal});
    }

    ButtonApprovalSet1 = (data,params) => {
        let { selectData,ButtonApprovalCal,modalName } = this.props;
        selectData.map(item=> {
            item.billTypeId = modalName;
            if(modalName=="Promoter"||modalName=="PromoterCommission"){
                item.organizationId = item.branchbfficeId;
            }else if(modalName=="RetailOrdersMonth"){
                item.organizationId = item.pkOrgId;
            }
        })
        let param1 = {
            ...params,
            callback: (res) =>{
                ButtonApprovalCal(res);
                this.setState({showLoading:false});
            }
        }
        let param = {
            data: selectData,
            header: {
                url: data.url,
                method: data.method || "post",
            },
            loadingFalse:()=>{
                this.setState({showLoading:false});
            },
            callback: () =>{
                actions.ApprovalModel.ButtonSetsModel(param1);
            }
        }
        this.setState({showLoading:true});
        actions.ApprovalModel.ButtonSetsModel(param);
    }

    ButtonApprovalSet2 = (data,params) => {
        let { selectData,ButtonApprovalCal,modalName } = this.props;
        selectData.map(item=> {
            item.billTypeId = modalName;
            if(modalName=="Promoter"||modalName=="PromoterCommission"){
                item.organizationId = item.branchbfficeId;
            }else if(modalName=="RetailOrdersMonth"){
                item.organizationId = item.pkOrgId;
            }
        })
        let param = {
            ...params,
            loadingFalse:()=>{
                this.setState({showLoading:false});
            },
            callback: () =>{
                ButtonApprovalCal();
                this.setState({showLoading:false});
            }
        }
        this.setState({showLoading:true});
        actions.ApprovalModel.ButtonSetsModel(param);
    }

    ButtonApprovalSet = (data) => {
        let { selectData,ButtonApprovalCal,modalName } = this.props;
        let datatemp=[];
        selectData.map(item=> {
            item.billTypeId = modalName;
            if(modalName=="Promoter"||modalName=="PromoterCommission"){
                item.organizationId = item.branchbfficeId;
            }else if(modalName=="RetailOrdersMonth"){
                item.organizationId = item.pkOrgId;
            }
        })
        if(data.batch){
            selectData.map(item => {
                datatemp.push({
                    id: item.id,
                    ncts: item.ncts
                })
            })
        }else {
            datatemp = {
                id: selectData[0].id,
                ncts: selectData[0].ncts
            }
        }
        

        let param = {
            data: selectData,
            header: {
                url: data.url,
                method: data.method || "post",
            },
            callback:()=>{
                setTimeout(()=>{
                    this.setState({showLoading:false});
                })
                ButtonApprovalCal();
                //零售订单添加分布式锁
                if(modalName=="RetailOrder"){
                    //占用成功后，释放锁（审批的过程很快）
                    let unLockUrl = "/occ-b2b-order/b2b/retail-order/unLock";
                    this.approveLockRequest(selectData,unLockUrl);
                }
                
            },
            loadingFalse:()=>{
                this.setState({showLoading:false});
            }
        }
        this.setState({showLoading:true});
        actions.ApprovalModel.ButtonSetsModel(param);
    }

    initDisableFlag = () => {
        let { selectData,bpmService,modalName } = this.props;
        let disabledSetsFlag = {
            ButtonSubmit: true,
            ButtonCallback: true,
            ButtonApprove: true,
            ButtonCallBackApprove: true,
            ButtonCancelApprove: true,
            CheckApprove: true

        };

        if (!selectData || selectData.length == 0) {
            return disabledSetsFlag;
        }
        // if (selectData.length > 1 && modalName != "ImportContract" && modalName != "ImportPreApprove") {
        //     return disabledSetsFlag;
        // }
        if(!("state" in selectData[0])) {
            return;
        }
        let code,field;
        Object.keys(bpmService).forEach(function (item) {
            code = bpmService[item].code;
            field = bpmService[item].field;
            
            if (code.search(selectData[0][field]) != -1) {
                disabledSetsFlag[item] = false;
            }
        })
        
        return disabledSetsFlag;
    }

    openAlert = async (type) => {
        let {selectData,modalName} = this.props;
        //零售订单添加分布式锁
        if(selectData.length==1&&modalName=="RetailOrder"){
            let getByIdLockUrl = "/occ-b2b-order/b2b/retail-order/getByIdLock";
            let res = await this.approveLockRequest(selectData,getByIdLockUrl);
            //进行审批的时候占用锁
            if(res&&res.data.status==0){
                Message.create({ content: res.data.message+"正在操作该单据，请稍后重试！", color: 'warning' });
                return;
            }
        }
        let verifyState;
        selectData.map((item,index) => {
            selectData.map((item1,index1) => {
                if(!("state" in item)) {
                    verifyState="选择的数据没有审批状态";
                }
                if(index != index1 && item.state != item1.state) {
                    verifyState="选择的数据审批状态不统一";
                }
            })
        })

        if(verifyState) {
            Message.create({ content: verifyState, color: 'warning' });
            return;
        }
        this.setState({
            ButtonType:type,
            showApprovalModalModal:true
        })
        
    }

    //审批调用分布式锁的接口
    approveLockRequest = async (selectData,getByIdLockUrl) => {
        let param ={
            planId:selectData[0].id,
            userId: JSON.parse(localStorage.getItem('loginUserInfo')).appUser.id
        }
        let ajax = {
            param:param,
            method:"get"
        }
        let res = await request(getByIdLockUrl,ajax)
        return res;
    }

    onClickCheckApprove = () => {
        let {selectData,bpmService,ButtonApprovalCal} = this.props;
        let {showApprovalListModal} = this.state;
        let self = this;
        let param = {
            params: {billId:selectData[0].id},
            header: {
                url: bpmService["CheckApprove"].url,
                method: bpmService["CheckApprove"].method || "get",
            },
            callback:(data)=>{
                setTimeout(()=>{
                    self.setState({
                        showApprovalListModal:!showApprovalListModal,
                        ButtonType:"CheckApprove",
                        approveList:data.body,
                        showLoading:false
                    })
                })
                // ButtonApprovalCal();
            },
            loadingFalse:()=>{
                this.setState({showLoading:false});
            }
        }
        this.setState({showLoading:true});
        actions.ApprovalModel.ButtonSetsModel(param);
    }

    render() {
        let { showApprovalModalModal,ButtonType,showLoading,showApprovalListModal,approveList=[] } = this.state;
        let {bpmService,selectData,billType,printTemplateId,modalName} = this.props;
        let disabledSetsFlag = this.initDisableFlag() || {};
       
        let authCodeList = JSON.parse(sessionStorage.getItem(`${modalName}`) || '[]');
        return (
            <>
                <ButtonGroup>
                    
                    {bpmService.ButtonSubmit &&  authCodeList.indexOf(bpmService.ButtonSubmit.authCode)!==-1 && 
                        <Button
                            shape='border' 
                            disabled={disabledSetsFlag["ButtonSubmit"]} 
                            onClick={() => this.openAlert("ButtonSubmit")} 
                            size='sm'>
                            提交
                        </Button>
                    }
                    {bpmService.ButtonCallback &&  authCodeList.indexOf(bpmService.ButtonCallback.authCode)!==-1 && <Button shape='border' disabled={disabledSetsFlag["ButtonCallback"]} onClick={() => this.openAlert("ButtonCallback")} size='sm' >
                        收回
                    </Button>}
                    {bpmService.ButtonApprove &&  authCodeList.indexOf(bpmService.ButtonApprove.authCode)!==-1 && <Button shape='border' disabled={disabledSetsFlag["ButtonApprove"]} onClick={() => this.openAlert("ButtonApprove")} size='sm' >
                        审批
                    </Button>}
                    {bpmService.ButtonCallBackApprove &&  authCodeList.indexOf(bpmService.ButtonCallBackApprove.authCode)!==-1 && <Button shape='border' disabled={disabledSetsFlag["ButtonCallBackApprove"]} onClick={() => this.openAlert("ButtonCallBackApprove")} size='sm' >
                        撤销审批
                    </Button> }
                    {bpmService.ButtonCancelApprove &&  authCodeList.indexOf(bpmService.ButtonCancelApprove.authCode)!==-1 && <Button shape='border' disabled={disabledSetsFlag["ButtonCancelApprove"]} onClick={() => this.openAlert("ButtonCancelApprove")} size='sm' >
                        取消审批
                    </Button>}
                    {bpmService.CheckApprove &&  authCodeList.indexOf(bpmService.CheckApprove.authCode)!==-1 && <Button disabled={disabledSetsFlag["CheckApprove"]} shape='border'  onClick={this.onClickCheckApprove} size='sm' >
                        查看审批流
                    </Button>}
                </ButtonGroup>
                <Loading show={showLoading} />
                <ApprovalModal 
                    ButtonType={ButtonType}
                    selectData={selectData}
                    bpmService={bpmService}
                    billType = {billType}
                    modalName = {modalName}
                    printTemplateId={printTemplateId}
                    showApprovalModalModal={showApprovalModalModal}
                    onCloseApproval = {this.onCloseApproval}
                 />
                <ShowApprovalModal 
                    selectData={selectData}
                    approveList={approveList}
                    showApprovalListModal={showApprovalListModal}
                    onCloseApproval = {this.onCloseApproval}
                    {...this.props}
                 />
            </>
        )
    }
}
Approval.propTypes = propTypes;
Approval.defaultProps = defaultProps;

export const PurchaseApprovalButton = connect(state => state.ClientApplyMonitorSample, null)(Approval);
